<template>
  <a-drawer
    v-model:open="drawerStatus"
    :centered="true"
    size="large"
    title="直播自动化配置"
    placement="right"
    @after-open-change="afterOpenChange"
  >
    <div class="add_live_config">
      <a-button class="add_live_config_btn" type="primary" @click="openModal">
        添加配置
      </a-button>
      <a-popconfirm title="确定要清空所有配置吗?" @confirm="clearConfig">
        <a-button class="add_live_config_btn" type="primary">
          清空配置
        </a-button>
      </a-popconfirm>
    </div>
    <a-table
      class="live_config_table"
      :columns="columns"
      :data-source="app.configFrom"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex == 'status'">
          <span v-if="app.isExecuteConfigId == record.id" style="color: green">
            执行中
          </span>
          <span v-else style="color: red"> 暂停 </span>
        </template>
        <template v-if="column.dataIndex == 'action'">
          <a-dropdown :trigger="['click']">
            <template #overlay>
              <a-menu @click="handleMenuClick($event, record)">
                <a-menu-item key="1"> 编辑 </a-menu-item>
                <a-menu-item key="2">
                  <span
                    v-if="app.isExecuteConfigId == record.id"
                    style="color: red"
                  >
                    暂停
                  </span>
                  <span v-else style="color: green"> 开启 </span>
                </a-menu-item>
                <a-menu-item key="3"> 删除 </a-menu-item>
              </a-menu>
            </template>
            <a-button>
              操作
              <DownOutlined />
            </a-button>
          </a-dropdown>
        </template>
      </template>
    </a-table>
  </a-drawer>

  <liveConfigPop
    ref="liveConfigPopRef"
    @updateConfig="updateConfig"
  ></liveConfigPop>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useApptore } from "../stores/app";
import liveConfigPop from "./liveConfigPop.vue";
import { ColumnsType } from "ant-design-vue/es/table";
import { DownOutlined } from "@ant-design/icons-vue";
import { useExecute } from "./useExecute";
import { notification } from "ant-design-vue";

const { start, stop } = useExecute();

const app = useApptore();

const liveConfigPopRef = ref();

const drawerStatus = ref<boolean>(false);

const columns: ColumnsType = [
  {
    title: "配置名称",
    dataIndex: "configName",
  },
  {
    title: "配置状态",
    dataIndex: "status",
  },
  {
    title: "配置操作",
    dataIndex: "action",
  },
];

const afterOpenChange = (bool: boolean) => {
  console.log("open", bool);
};

function handleMenuClick(e: any, data: any) {
  if (e.key == 1) {
    if (app.isExecuteConfigId && app.isExecuteConfigId == data.id) {
      notification["info"]({
        message: "程序执行中",
        description: "正在执行中的程序无法编辑",
        onClick: () => {
          console.log("Notification Clicked!");
        },
      });
      return;
    }
    liveConfigPopRef.value.open(data);
  } else if (e.key == 2) {
    changeExecuteStatus(data);
  } else if (e.key == 3) {
    deleteItem(data.id);
  }
}

function updateConfig(data: any) {
  let configData = JSON.parse(JSON.stringify(data));
  let configIndex = app.configFrom.findIndex((item) => data.id == item.id);
  if (configIndex != -1) {
    app.configFrom.splice(configIndex, 1);
  } else {
    configData = { ...data, id: generateUUID() };
  }
  app.configFrom.unshift(configData);
}

function deleteItem(id: string) {
  let configIndex = app.configFrom.findIndex((item) => id == item.id);
  if (configIndex != -1) {
    app.configFrom.splice(configIndex, 1);
  }
}

/**
 * 修改自动化程序的执行状态
 */
function changeExecuteStatus(data: any) {
  if (!app.isExecuteConfigId) {
    start(data);
  } else if (app.isExecuteConfigId && app.isExecuteConfigId == data.id) {
    stop();
  } else {
    notification["info"]({
      message: "程序执行中",
      description: "当前已有程序，正在执行，无法启动当前程序",
      onClick: () => {
        console.log("Notification Clicked!");
      },
    });
  }
}

function openModal() {
  liveConfigPopRef.value.open();
}

function open() {
  drawerStatus.value = true;
}

function clearConfig() {
  console.log("clearConfig");
  app.configFrom = [];
}

function generateUUID() {
  // 回退方案
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

defineExpose({
  open,
  close,
});
</script>

<style scoped lang="less">
.add_live_config {
  display: flex;
  width: 100%;
  .add_live_config_btn {
    margin-left: 10px;
    display: block;
  }
}

.live_config_table {
  margin-top: 20px;
}
</style>
